package com.tidc.deleteprovider.service;


import com.tidc.commonality.api.AuthenticationApi;
import com.tidc.deleteprovider.exception.PeyondPowerException;
import com.tidc.deleteprovider.mapper.*;
import com.tidc.deleteprovider.ov.UserOV;
import com.tidc.deleteprovider.pojo.*;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassNmae DeleteService
 * @Description TODO
 * @Author 14631
 **/
@Service
public class DeleteService {
	@Autowired
	private WorksMaper worksMaper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ScoreMapper scoreMapper;
	@Autowired
	private TeamMapper teamMapper;
	@Autowired
	private MatchsMapper matchsMapper;
	AuthenticationApi authenticationApi;
	public UserOV deleterWork(int id, UserOV userOV,String token) throws NotFoundException {
//		首先就是查询这个项目存不存在还要附上用户id去查
		Student student = userMapper.selectStudent(((Student)authenticationApi.userInfo(token)).getEmail());
		Map map = new HashMap();
		map.put("id",id);
		map.put("works_student_id",student.getId());
		Works works = worksMaper.selectStudentWorks(map);
		if(works==null){
			throw new NotFoundException(student.getName()+"试图删除id为"+id+"的项目但是没有查找到这个项目于也可能是这个人试图越权删除别人的项目");
		}
//		删除这个项目的分数数据
		scoreMapper.deleteScore(works.getId());
//		清空这个项目的比赛成员和将队伍数据删除由于数据库问题删除的时候需要置空一些字段
		teamMapper.deleteTeamMembers(works.getWorks_team_id());
		teamMapper.setTeamWorksIdNUll(works.getWorks_team_id());
		worksMaper.setWorksTeamIdNull(works.getId());
		teamMapper.deleteTeam(works.getWorks_team_id());
//		删除比赛
		worksMaper.deleteWorks(works.getId());
		return userOV.setData(null).setMessage("删除成功").setCode(200);

	}
	public UserOV deleteMember(int teamId,int studentId,UserOV userOV,String token){
		Student student = userMapper.selectStudent(((Student)authenticationApi.userInfo(token)).getEmail());
		Member member = new Member();
		member.setMember_student_id(studentId);
		member.setMember_team_id(teamId);
		teamMapper.deleteMember(member);
		return userOV.setCode(200);
	}
	public UserOV deletePower(int matchId,int teacherId,UserOV userOV,UserDetails userDetails) throws PeyondPowerException {
		Teacher teacher = userMapper.selectTeacher(userDetails.getUsername());
		Matchs matchs = matchsMapper.selectMatchs(matchId);
		if(!(matchs.getTeacher_id()==teacher.getId())){
			throw new PeyondPowerException(teacher.getUserName(),teacher.getId());
		}
		matchsMapper.deletePower(teacherId);
		return userOV.setCode(200);
	}
}
